<?php

namespace app\common\model;

use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\facade\Validate;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 用户信息表
 */
class trUser extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "user"; //表名

    protected $type = [
        'update_time'  =>  'timestamp:Y-m-d H:i',
        'register_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(isset($item["avatar"])){
                    if(!trim($item["avatar"])) {
                        $data[$k]["avatarId"] = "/attachment/default/avatar.png";
                        $data[$k]["avatar"] = tome_dia("/attachment/default/avatar.png?v=1");
                    }else{
                        $data[$k]["avatarId"] = $item["avatar"];
                        if(strpos($item["avatar"], "http") === false) {
                            $data[$k]["avatar"] = tome_dia(trResource::getValue("url", ["id" => $item["avatar"]]));
                        }
                    }
                }
                if(isset($item["gender"])){ // 性别：1男；2女
                    $data[$k]["genderText"] = $this->getAttrByGender($item["gender"]);
                }
                if(isset($item["status"])){ // 状态：1正常；2锁定；3注销
                    $data[$k]["statusText"] = $this->getAttrByStatus($item["status"]);
                }
            }
        }else{
            if(isset($data["avatar"])) {
                if (!trim($data["avatar"])) {
                    $data["avatarId"] = "/attachment/default/avatar.png";
                    $data["avatar"] = tome_dia("/attachment/default/avatar.png?v=1");
                } else {
                    $data["avatarId"] = $data["avatar"];
                    if (strpos($data["avatar"], "http") === false) {
                        $data["avatar"] = tome_dia(trResource::getValue("url", ["id" => $data["avatar"]]));
                    }
                }
            }

            if(isset($data["gender"])){ // 性别：1男；2女
                $data["genderText"] = $this->getAttrByGender($data["gender"]);
            }
            if(isset($data["status"])){ // 状态：1正常；2锁定；3注销
                $data["statusText"] = $this->getAttrByStatus($data["status"]);
            }
        }
        return $data;
    }

    public function getAttrByGender($gender){
        switch ($gender){
            case "1":
                return "男";
                break;
            case "2":
                return "女";
                break;
            default:
                return "未知";
                break;
        }
    }

    public function getAttrByStatus($status){ // 状态：1正常；2锁定；3注销
        switch ($status){
            case "1":
                return "已启用";
                break;
            case "2":
                return "已冻结";
                break;
            case "3":
                return "已注销";
                break;
            default:
                return "未知";
                break;
        }
    }

    //分页获取所有字段数据
    public function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "register_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = $this->transferField($data["data"]);
                return $data;
            }
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = $this->transferField($data->toArray());
            return $data;
        }
        return [];
    }

    //根据条件获取数量
    public function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    //添加
    public function add($data, $getId=false){
        if(!$data)
            return true;
        try {
            $data["mall_id"] = request()->mallData["id"];
            //判断手机号是否重复
            if(!empty($data["mobile"])){
                if(!Validate::isMobile($data["mobile"])){
                    return ErrorCode::code("params_format", "mobile");
                }
                if($this->getCount(["mobile" => $data["mobile"], "mall_id" => $data["mall_id"]])){
                    return ErrorCode::code("mobile_exist");
                }
            }
            //判断邮箱是否重复
            if(!empty($data["email"])){
                if(!Validate::isEmail($data["email"])){
                    return ErrorCode::code("params_format", "email");;
                }
                if($this->getCount(["email" => $data["email"], "mall_id" => $data["mall_id"]])){
                    return ErrorCode::code("email_exist");
                }
            }
            do{
                $data["number_id"] = substr(str_shuffle(str_repeat("0123456789", 10)), 0, 10);
            }while($this->getCount(["number_id" => $data["number_id"]]));
            if(empty($data["update_time"])) $data["update_time"] = time();
            if ($getId) {
                $model = self::create($data);
                return $model->id;
            } else {
                return self::save($data);
            }
        }catch (\Exception $e){
            return ErrorCode::code("try_error", $e->getMessage());
        }
    }

    //更新
    public function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        if(!isset($filter["id"])){
            $filter["id"] = $this->getValue("id", $filter);
        }
        //判断手机号是否重复
        if(!empty($data["mobile"])){
            if(!Validate::isMobile($data["mobile"])){
                return ErrorCode::code("params_format", "mobile");
            }
            if($this->getCount([["mobile", '=', $data["mobile"]], ["id", '<>', $filter["id"]], ["mall_id", "=", request()->mallData["id"]]])){
                return ErrorCode::code("mobile_exist");
            }
        }
        //判断邮箱是否重复
        if(!empty($data["email"])){
            if(!Validate::isEmail($data["email"])){
                return ErrorCode::code("params_format", "email");
            }
            if($this->getCount([["email", '=', $data["email"]], ["id", '<>', $filter["id"]], ["mall_id", "=", request()->mallData["id"]]])){
                return ErrorCode::code("email_exist");
            }
        }
        if(empty($data["update_time"])) $data["update_time"] = time();
        if(self::save($data, $filter)){
            if((isset($data["status"]))){
                $cacheList = [];
                if($redisObject = redis_object() !== false) { // 用redis缓存
                    $cache = $redisObject->getKeys("user_login_{$filter["id"]}_*");
                    if (!$cache) {
                        foreach ($cache as $item) {
                            $cacheList[] = $redisObject->get($item);
                        }
                    }
                }else{ // 非redis,查询数据库
                    $base = trCache::where("key", "like", "user_login_{$filter["id"]}_%")->where("mall_id", request()->mallData["id"])->column("value");
                    foreach ($base as $item) {
                        $cacheList[] = unserialize($item);
                    }
                }
                foreach ($cacheList as $id) {
                    if ($cacheData = cache("web_" . $id)) {
                        if (isset($data["status"]))
                            $cacheData["status"] = $data["status"];
                        cache("web_" . $id, $cacheData, 86400); // 用户小程序登录缓存的数据，更新司机身份和用户状态
                    }
                }
            }
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::where($filter)->value($field);
        }
        return false;
    }

    //获取某字段的所有值
    public function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //获取多字段数据
    public function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : $data) : [];
        }
    }

    //根据ID删除数据
    public function delById($id){
        if(is_array($id)){
            $result = self::where('id', 'in', $id)->where("mall_id", request()->mallData["id"])->delete();
        }else{
            $result = self::where('id', $id)->where("mall_id", request()->mallData["id"])->delete();
            $id = [$id];
        }
        if($result){
            foreach ($id as $i){
                trCache::delByVague("user_login_{$i}_");
                commonModel::delByFilter(contactTable, ["user_id" => $i]);
                commonModel::delByFilter(formIdTable, ["user_id" => $i]);
                commonModel::delByFilter(userCouponTable, ["user_id" => $i]);
            }
            trUserToken::delByUserId($id);
        }
        return $result;
    }
}